package com.briup.bookstore.common.model.vo;

import com.briup.bookstore.common.model.entity.Order;
import com.briup.bookstore.common.model.entity.OrderItem;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author YuYan
 * @date 2023-12-27 20:54:12
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class OrderVO {

    @JsonProperty("orderId")
    private String id;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Shanghai")
    private Date createDate;
    private String payWay;
    private Integer trackingNumber;
    private String distributionMode;
    private Integer status;
    private Double totalPrice;
    private Integer totalNum;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Shanghai")
    private Date payDate;
    private String receiveUsername;
    private String receiveAddress;
    private String receivePhone;
    private String username;
    private List<OrderItemVO> orderItems;
    public static OrderVO toVO(Order order) {
        return OrderVO.builder()
                .id(order.getId())
                .createDate(order.getCreateDate())
                .payWay(order.getPayWay())
                .trackingNumber(order.getTrackingNumber())
                .distributionMode(order.getDistributionMode())
                .status(order.getStatus())
                .totalPrice(order.getOrderItems()
                        .stream()
                        .map(orderItem -> orderItem.getBook().getPrice() * orderItem.getNum())
                        .reduce(Double::sum)
                        .orElse(0.0D))
                .totalNum(order.getOrderItems()
                        .stream()
                        .map(OrderItem::getNum)
                        .reduce(Integer::sum)
                        .orElse(0))
                .payDate(order.getPayDate())
                .receiveUsername(order.getReceiveUsername())
                .receiveAddress(order.getReceiveAddress())
                .receivePhone(order.getReceivePhone())
                .username(order.getUser().getUsername())
                .orderItems(order.getOrderItems()
                        .stream()
                        .map(OrderItemVO::toVO)
                        .collect(Collectors.toList()))
                .build();
    }
}
